import os
import subprocess
import sys
from ogreEx.blender.props import StringProperty
from ogreEx.blender.types import Operator
from ogreEx.config import getConfig
from ogreEx.ogre.C_OgreCommonExport_ import _OgreCommonExport_

from ogreEx.ui.UIClass import OPERATOR

def JmonkeyPipe( path ):
    root = getConfig()[ 'JMONKEY_ROOT']
    if sys.platform.startswith('win'):
        cmd = [ os.path.join( os.path.join( root, 'bin' ), 'jmonkeyplatform.exe' ) ]
    else:
        cmd = [ os.path.join( os.path.join( root, 'bin' ), 'jmonkeyplatform' ) ]
    cmd.append( '--nosplash' )
    cmd.append( '--open' )
    cmd.append( path )
    proc = subprocess.Popen(cmd)#, stdin=subprocess.PIPE)
    return proc

## Jmonkey preview
## todo: remove jmonkey

@OPERATOR
class JmonkeyPreviewOp(_OgreCommonExport_, Operator):
    '''helper to open jMonkey (JME)'''
    bl_idname = 'jmonkey.preview'
    bl_label = "opens JMonkeyEngine in a non-blocking subprocess"
    bl_options = {'REGISTER'}

    filepath= StringProperty(name="File Path", description="Filepath used for exporting Jmonkey .scene file", maxlen=1024, default="/tmp/preview.txml", subtype='FILE_PATH')
    EXPORT_TYPE = 'OGRE'

    @classmethod
    def poll(cls, context):
        if context.active_object: return True

    def invoke(self, context, event):
        path = '/tmp/preview.scene'
        self.ogre_export( path, context )
        JmonkeyPipe( path )
        return {'FINISHED'}
